using System;
using System.Collections.Generic;
using Microsoft.Practices.Unity;

namespace UniAspect.UnityCommon
{
    /// <summary>
    /// Use with caution, as this works only
    /// when calling Resolve from different threads
    /// </summary>
    public class PerThreadLifetimeManager : LifetimeManager
    {
        [ThreadStatic]
        private static Dictionary<PerThreadLifetimeManager, object> _values;

        public override object GetValue()
        {
            Initialize();
            if(_values.ContainsKey(this))
            {
                return _values[this];
            }
            return null;
        }

        public override void SetValue(object newValue)
        {
            Initialize();
            _values[this] = newValue;
        }

        public override void RemoveValue()
        {
            
        }

        /// <summary>
        /// Gotta call this 'cuz _values field is initialized only once in the main thread.
        /// </summary>
        private void Initialize()
        {
            if(_values == null)
            {
                _values = new Dictionary<PerThreadLifetimeManager, object>();
            }
        }
    }
}